<?php


namespace app\appapi\controller;

// if (isset($_SERVER['HTTP_ORIGIN'])) {
//     header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
//     header("Access-Control-Allow-Credentials: true");
//     header("Access-Control-Max-Age: 86400");
// }
// if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
//     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
//         header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
//     }
//     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
//         header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
//     }
//     exit();
// }

use app\common\controller\SmsController;
use app\common\model\ArticleModel;
use app\common\model\GoodsModel;
use app\common\model\OrderModel;
use app\common\model\OrderReceiptModel;
use app\common\model\SlideItemModel;
use app\common\model\SmsCodeModel;
use app\common\model\StorageManageModel;
use app\common\model\UserModel;
use cmf\controller\RestBaseController;
use GuzzleHttp\Client;
use think\Db;
use think\db\Query;
use think\Request;
use app\common\model\RechargeModel;
use app\common\model\MoneyLogModel;


class IndexController extends RestBaseController
{
    public function index()
    {
    }

    public function get_index_info()
    {
        $banner = SlideItemModel::getslide(1);
        $btm_pic = SlideItemModel::getslide(2);
        $hot_pic = SlideItemModel::getslide(3);
        $new_goods = GoodsModel::newgoods();
        $new_pic = SlideItemModel::getslide(4);
        $news = ArticleModel::news(1);
        $top_goods = GoodsModel::topgoods();
        $this->success('ok', compact('banner', 'btm_pic', 'hot_pic', 'new_goods', 'new_pic', 'news', 'top_goods'));
    }

    public function login($phone, $password)
    {

        if (empty($phone)) {
            $this->error(lang('USERNAME_OR_EMAIL_EMPTY'));
        }
        if (empty($password)) {
            $this->error(lang('PASSWORD_REQUIRED'));
        }

        $result = UserModel::where('user_login', $phone)->find();
        if (!empty($result) && $result['user_type'] == 2) {
            if (cmf_compare_password($password, $result['user_pass'])) {
                //登入成功页面跳转
                session('USER_ID', $result["id"]);
                $result['last_login_ip'] = get_client_ip(0, true);
                $result['last_login_time'] = time();
                $token = cmf_generate_user_token($result["id"], 'web', 1);
                if (!empty($token)) {
                    session('USER_TOKEN', $token);
                    $result['token'] = $token;
                }
                $info = $result->toArray();
                $result->save($result);
                cookie("username", $phone, 3600 * 24 * 30);
                $this->success('登录成功', $info);
            } else {
                $this->error(lang('PASSWORD_NOT_RIGHT'));
            }
        } else {
            $this->error(lang('USERNAME_NOT_EXIST'));
        }
    }

    public function send_sms($phone, $is_type = 1)
    {
        if (!cmf_check_mobile($phone)) {
            $this->error('手机号格式错误');
        }

        $bool = UserModel::where('user_login', $phone)->find();
        if ($bool && $is_type == 1) {
            $this->error('已被注册');
        }

        $bool = SmsCodeModel::where(['phone' => $phone, 'status' => 0])->find();
        // if ($bool && $bool['create_time'] + 60 * 5 > time()) {
        if ($bool && $bool['create_time'] + 5 > time()) {
            $this->error('验证码还在有效期');
        }

        $count = SmsCodeModel::where('phone', $phone)->whereTime('create_time', 'd')->count();
        if ($count >= 5) {
            $this->error('今日发送已达上限');
        }

        $code = random(4, true);
        // $res = send_code($phone, $code);
        $res = sendSms($phone, $code, 'register');
        file_put_contents('./smslog.txt', date('Y/m/d H:i:s').PHP_EOL."电话{$phone}|验证码{$code}|结果：".var_export($res, true).PHP_EOL, FILE_APPEND);
//        $res = SmsController::sendAliCode($phone, $code);
        if ($res['code'] == 1) {
//            session('phone_code', $code);
//            $scode = session('phone_code');
//            file_put_contents('./smslog.txt', '第一次获取session——code——'.$scode.PHP_EOL, FILE_APPEND);
            SmsCodeModel::create(['phone' => $phone, 'code' => $code, 'status' => 0, 'create_time' => time(), 'update_time' => time(), 'ip' => $this->request->ip()]);
            $this->success($res['msg']);
        }
        $this->error($res['msg']);
    }

    protected function check_code($phone, $code)
    {
//        file_put_contents('./smslog.txt', '第二次获取session——code——'.session('phone_code').PHP_EOL, FILE_APPEND);
//        if (!session('phone_code')) {
//            $this->error('请先获取验证码');
//        }
//        if ($code != session('phone_code')) {
//            $this->error('验证码错误');
//        }
//        session('phone_code', null);
        $bool = SmsCodeModel::where(['phone' => $phone, 'status' => 0])->find();
        // if ($bool && $bool['create_time'] + 60 * 5 > time()) {
        if ($bool && $bool['create_time'] + 300 < time()) {
            SmsCodeModel::where('id', $bool['id'])->delete();
            $this->error('验证码已过期');
        }
        if ($bool['code'] != $code) $this->error('验证码错误');

        SmsCodeModel::where('id', $bool['id'])->update(['update_time' => time(), 'status' => 1]);
        return true;
    }

    public function register($phone, $password, $code = '')
    {
        $this->check_code($phone, $code);

        if (!cmf_check_mobile($phone)) {
            $this->error('请填写正确手机号');
        }
        if (!cmf_check_pass($password)) {
            $this->error('密码至少6位字符，且必须包含数字和字母');
        }
        $bool = UserModel::where('user_login', $phone)->find();
        if ($bool) {
            $this->error('手机号已经注册过了');
        }

        $r = UserModel::create([
            'user_login'    => $phone,
            'user_pass'     => cmf_password($password),
            'user_type'     => 2,
            'user_nickname' => $phone . '_' . cmf_random_string(4)
        ]);
        if ($r) {
            $this->success('注册成功');
        } else {
            $this->error('注册失败');
        }
    }

    public function forget_password(Request $request)
    {
        $this->check_code($request->phone, $request->code);

        if (!cmf_check_pass($request->password)) {
            $this->error('密码必须是6-20位数字字母组成');
        }

        $user = UserModel::where('user_login', $request->phone)->find();
        if (cmf_password($request->password) == $user['user_pass']) {
            $this->error('新密码不能和旧密码一样');
        }

        if ($user->save(['user_pass' => cmf_password($request->password)])) {
            $this->success('ok');
        } else {
            $this->error('修改失败');
        }

    }

    public function excel(Request $request)
    {
        ini_set('memory_limit', '256M');
        $param = $request->param();
        $list = OrderReceiptModel::where(function (Query $query) use ($param) {
            $query->where('show_status', 1);
            if (!empty($param['keyword'])) {
                $query->where('obtain_order_id|self_order_no', $param['keyword']);
            }
            if (!empty($param['status'])) {
                $query->where('order_status', $param['status']);
            }
        })->order('id desc')->select()->toArray();

        if (!$list) {
            $this->error('没有包裹信息');
        }

        $fileName = '包裹信息' . date('ymdHis') . '.csv';

        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        $fp = fopen('php://output', 'a');
        $head = ['包裹编号', '订单编号', '运单号', '快递公司', '收货人', '收货人电话', '收货地址', '备注信息'];
        mb_convert_variables('GBK', 'UTF-8', $head);
        fputcsv($fp, $head);
        foreach ($list as $item) {
            $row = [$item['self_order_no'], $item['obtain_order_no'], $item['delivery_no'], $item['delivery_company'], $item['name'], $item['tel'], $item['area_info'], $item['title']];
            mb_convert_variables('GBK', 'UTF-8', $row);
            fputcsv($fp, $row);
            unset($row);
        }
        fclose($fp);
        die();
    }

    public function fm_notify()
    {
        $paySettings =  cmf_get_option('pay_settings');
        $merchantNum = $paySettings['mchid'];
        $secret = $paySettings['secret'];

        cmf_log("FM支付回调【{$_GET['orderNo']}】：" . date("Y-m-d H:i:s") . PHP_EOL . var_export($_GET, true).PHP_EOL, 'pay.log');
        $sign = $this->rebacksign(array($_GET['state'], $merchantNum, $_GET['orderNo'], $_GET['amount'], $secret));

        if ($merchantNum == $_GET['merchantNum'] && $sign == $_GET['sign']) {
            $log = RechargeModel::get(['order_no' => $_GET['orderNo']]);
            if ($log->status == 1) {
                cmf_log("FM支付回调【{$_GET['orderNo']}】：已经成功了" . date("Y-m-d H:i:s") . PHP_EOL, 'pay.log');
                exit('success');
            }

            Db::startTrans();
            $ret = $log->save(['status' => 1, 'trade_no' => $_GET['platformOrderNo'], 'uptime' => time()]);
            if (!$ret) {
                Db::rollback();
                cmf_log("FM支付回调【{$_GET['orderNo']}】：充值记录更新失败" . date("Y-m-d H:i:s") . PHP_EOL, 'pay.log');
                $this->error('充值记录更新失败');
            }

            $ret = MoneyLogModel::addLog($log['user_id'], $_GET['actualPayAmount'], 2, 'FM充值', $log['order_no']);
            if (!$ret) {
                Db::rollback();
                cmf_log("FM支付回调【{$_GET['orderNo']}】：充值记录更新失败" . date("Y-m-d H:i:s") . PHP_EOL, 'pay.log');
                $this->error('充值记录更新失败');
            }

            Db::commit();
            cmf_log("FM支付回调【{$_GET['orderNo']}】：充值成功" . date("Y-m-d H:i:s") . PHP_EOL, 'pay.log');
            exit('success');
        } else {
            cmf_log("FM支付验签失败【{$_GET['orderNo']}】：" . date("Y-m-d H:i:s") . PHP_EOL . "商户号：{$merchantNum}|{$_GET['merchantNum']}，签名：{$sign}|{$_GET['sign']}".PHP_EOL, 'pay.log');
            exit('fail');
        }
    }

    /**
     * md5(付款成功状态state的值+商户号merchantNum的值+商户订单号orderNo的值+订单金额amount的值+商户秘钥)
     */
    protected function rebacksign($data_arr)
    {
        cmf_log("FM支付回调签名：" . date("Y-m-d H:i:s") . PHP_EOL . join('+', $data_arr) . "== MD5sign ==> " . md5(join('', $data_arr)).PHP_EOL, 'pay.log');
        return md5(join('', $data_arr));
    }


}
